const Todo = require('../models/Todo');
const errorHandler = require('../middleware/error');

// @desc    Get all todos
// @route   GET /api/todos
// @access  Public
exports.getTodos = async (req, res, next) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      completed, 
      category, 
      priority, 
      sortBy = 'createdAt', 
      sortOrder = 'desc',
      search
    } = req.query;

    // 构建查询条件
    let query = {};
    
    // 完成状态筛选
    if (completed !== undefined) {
      query.completed = completed === 'true';
    }
    
    // 分类筛选
    if (category) {
      query.category = category;
    }
    
    // 优先级筛选
    if (priority) {
      query.priority = priority;
    }
    
    // 搜索标题
    if (search) {
      query.title = { $regex: search, $options: 'i' };
    }

    // 构建排序条件
    let sort = {};
    sort[sortBy] = sortOrder === 'asc' ? 1 : -1;

    // 执行查询
    const todos = await Todo.find(query)
      .sort(sort)
      .limit(limit * 1)
      .skip((page - 1) * limit);

    // 获取总数用于分页
    const total = await Todo.countDocuments(query);

    res.status(200).json({
      success: true,
      count: todos.length,
      total,
      page: parseInt(page),
      pages: Math.ceil(total / limit),
      data: todos
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Get single todo
// @route   GET /api/todos/:id
// @access  Public
exports.getTodo = async (req, res, next) => {
  try {
    const todo = await Todo.findById(req.params.id);

    if (!todo) {
      return res.status(404).json({
        success: false,
        error: 'Todo not found'
      });
    }

    res.status(200).json({
      success: true,
      data: todo
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Create new todo
// @route   POST /api/todos
// @access  Public
exports.createTodo = async (req, res, next) => {
  try {
    const todo = await Todo.create(req.body);

    res.status(201).json({
      success: true,
      data: todo
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Update todo
// @route   PUT /api/todos/:id
// @access  Public
exports.updateTodo = async (req, res, next) => {
  try {
    const todo = await Todo.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
      runValidators: true
    });

    if (!todo) {
      return res.status(404).json({
        success: false,
        error: 'Todo not found'
      });
    }

    res.status(200).json({
      success: true,
      data: todo
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Delete todo
// @route   DELETE /api/todos/:id
// @access  Public
exports.deleteTodo = async (req, res, next) => {
  try {
    const todo = await Todo.findByIdAndDelete(req.params.id);

    if (!todo) {
      return res.status(404).json({
        success: false,
        error: 'Todo not found'
      });
    }

    res.status(200).json({
      success: true,
      data: {}
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Toggle todo completion status
// @route   PATCH /api/todos/:id/complete
// @access  Public
exports.toggleComplete = async (req, res, next) => {
  try {
    const todo = await Todo.findById(req.params.id);

    if (!todo) {
      return res.status(404).json({
        success: false,
        error: 'Todo not found'
      });
    }

    // 切换完成状态
    todo.completed = !todo.completed;
    if (todo.completed) {
      todo.completedAt = Date.now();
    } else {
      todo.completedAt = null;
    }
    
    await todo.save();

    res.status(200).json({
      success: true,
      data: todo
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Get calendar view data
// @route   GET /api/todos/calendar
// @access  Public
exports.getCalendarTodos = async (req, res, next) => {
  try {
    const { startDate, endDate } = req.query;

    let query = {};
    
    // 如果提供了日期范围，筛选该范围内的任务
    if (startDate && endDate) {
      query.dueDate = {
        $gte: new Date(startDate),
        $lte: new Date(endDate)
      };
    }

    const todos = await Todo.find(query);

    res.status(200).json({
      success: true,
      data: todos
    });
  } catch (err) {
    next(err);
  }
};

// @desc    Batch operations
// @route   POST /api/todos/batch
// @access  Public
exports.batchTodos = async (req, res, next) => {
  try {
    const { action, ids } = req.body;

    if (!action || !ids || !Array.isArray(ids)) {
      return res.status(400).json({
        success: false,
        error: 'Action and ids array are required'
      });
    }

    let result;
    
    switch (action) {
      case 'complete':
        result = await Todo.updateMany(
          { _id: { $in: ids } },
          { completed: true, completedAt: Date.now() }
        );
        break;
      case 'delete':
        result = await Todo.deleteMany({ _id: { $in: ids } });
        break;
      default:
        return res.status(400).json({
          success: false,
          error: 'Invalid action. Supported actions: complete, delete'
        });
    }

    res.status(200).json({
      success: true,
      message: `Batch ${action} operation completed`,
      affected: result.modifiedCount || result.deletedCount
    });
  } catch (err) {
    next(err);
  }
};